import os.path
import re
import requests


class BaseApi:
    file_dir = None
    download_url = None
    download_name = None
    res = None
    title = None
    req = None
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                             'Chrome/103.0.5060.114 Safari/537.36 Edg/103.0.1264.49'}

    @classmethod
    def getSource(cls, url):
        cls.req = requests.request('get', url)
        cls.req.encoding = 'utf8'
        return cls.req.text

    @classmethod
    def searchName(cls, partten, source):
        cls.title = re.compile(partten, re.DOTALL)
        cls.res = cls.title.search(source)
        cls.download_name = cls.res.group(1)
        return cls.download_name

    @classmethod
    def combineUrl(cls, url, download_name):
        cls.download_url = f'{url}{download_name}'
        return cls.download_url

    @classmethod
    def cleanFile(cls, file_name):
        cls.file_dir = f'{file_name}/'
        if os.path.exists(f"{cls.file_dir}{file_name}.pdf"):
            os.remove(f"{cls.file_dir}{file_name}.pdf")

    @classmethod
    def downFile(cls, filetpye, file_name, url):
        try:
            if not os.path.exists(cls.file_dir):
                os.mkdir(cls.file_dir)
            text = requests.get(url, headers=cls.headers)
            f = open(f"{cls.file_dir}{file_name}.{filetpye}", 'wb')
            f.writelines(text)
            f.close()
        except Exception as e:
            print(f'文件：{file_name}下载出错,错误内容{e}')
